package com.kelvin.oocl.crm.bean.manager.context.impl;

import java.lang.reflect.Method;

import com.kelvin.oocl.crm.bean.manager.annotation.Bean;
import com.kelvin.oocl.crm.bean.manager.annotation.Config;
import com.kelvin.oocl.crm.bean.manager.context.ApplicationContext;
import com.kelvin.oocl.crm.util.MySimpleMap;

public class DefaultApplicationContext implements ApplicationContext {
	private MySimpleMap<String, Object> context = new MySimpleMap<>();
	
	public DefaultApplicationContext() {
		
	}

	@Override
	public void loadConfig(String classFullName) {
		if(null==classFullName){
			return;
		}
		try {
			Class<?> clazz = Class.forName(classFullName);
			boolean isConfig = clazz.isAnnotationPresent(Config.class);
			if(isConfig){
				Object obj = clazz.newInstance();
				Method[] methods = clazz.getMethods();
				for (Method method : methods) {
					boolean isBean = method.isAnnotationPresent(Bean.class);
					if(isBean){
						Bean bean = method.getAnnotation(Bean.class);
						String name = bean.name();
						Object object = method.invoke(obj, new Object[]{});
						if(object != null){
							context.put(name, object);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public <T> T findBean(String beanName,Class<T> type) {
		try {
			T t = (T) context.getKey(beanName);
			return t;
		} catch (Exception e) {
			return null;
		}
	}

}
